package com.atguigu.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.commom.helper.JwtHelper;
import com.atguigu.yygh.commom.result.Result;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantWeiXInPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.sun.deploy.net.URLEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mengWu
 * @Date 2021年05月26日 15:16
 * 微信操作接口
 * 实现的功能
 * 1、生成微信扫描的二维码
 * 2、回调方法，得到扫描人的信息
 */
@Api(tags = "微信扫码登录")
@Controller //不返回数据，进行页面的跳转
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {
    private UserInfoService userInfoService;

    private RedisTemplate redisTemplate;

    //构造方法注入
    public WeixinApiController(UserInfoService userInfoService, RedisTemplate redisTemplate) {
        this.userInfoService = userInfoService;
        this.redisTemplate = redisTemplate;
    }

    //微信扫码后的回调方法
    @GetMapping("callback")
    @ApiOperation(value = "微信扫码后的回调方法")
    public String callback(String code, String state){
        //1、获取到临时票据 -- code
        //2、拿着code和微信id和密钥，请求微信固定地址，得到两个值

        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWeiXInPropertiesUtil.WX_OPEN_APP_ID,
                ConstantWeiXInPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        //使用httpclient请求该地址
        try {
            String accesstokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accesstokenInfo："+accesstokenInfo);
            //从返回的结果中获取openid和access_token -- json工具
            JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            //判断数据库中是否已经存在微信扫码人的信息 -- 根据openid进行判断
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);

            if (userInfo == null){
                //3、拿着openid和access_token请求微信地址，得到扫描人信息

                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);

                String resultInfo = HttpClientUtils.get(userInfoUrl);

                System.out.println("resultInfo："+resultInfo);

                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);

                //解析用户信息
                //昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //头像
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                //获取扫码人的信息，添加到数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);

                userInfoService.save(userInfo);

            }


            //返回内容 -- name和token字符串
            Map<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            //判断userInfo中是否有手机号，如果手机号为空，返回openid
            //如果手机号不为空，返回openid的值是空字符串
            //前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //生成token
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            //页面跳转 -- redirect --重定向
            return "redirect:" + ConstantWeiXInPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");


        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    //返回二维码需要的参数
    @GetMapping("getLoginParam")
    @ApiOperation(value = "返回二维码需要的参数")
    @ResponseBody
    public Result genQrConnect() {

        try {
            String redirectUri = URLEncoder.encode(ConstantWeiXInPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantWeiXInPropertiesUtil.WX_OPEN_APP_ID);
            map.put("redirectUri", redirectUri);
            map.put("scope", "snsapi_login");
            map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
            return Result.ok(map);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

}
